<template>
    <div v-if="true" class="chat-container">
      <!-- 对话显示区域 -->
      <div class="chat-messages">
        <div v-for="(message, index) in messages" :key="index" class="message">
          <div :class="message.username === currentUsername? 'user-message' : 'other-message'">
            <span>{{ message.username }}: </span>
            <!-- 使用 v-html 渲染包含 Emoji 图片的消息 -->
            <span v-html="renderMessageWithEmoji(message.text)" @click="downloadFile(message)"></span>
          </div>
        </div>
      </div>
      <!-- 输入框和发送按钮 -->
      <div class="chat-input">
        <a-input v-model="inputMessage" placeholder="请输入消息" @keyup.enter="sendMessage" @input="handleInput" class="input-box"></a-input>
        <!-- 竖条选择菜单 -->
        <div v-if="isSlashMenuVisible" class="slash-menu">
          <div v-for="option in slashMenuOptions" :key="option.value" @click="selectOption(option)">
            {{ option.label }}
          </div>
        </div>
        <a-button @click="sendMessage" class="send-button">发送</a-button>
        <!-- 表情按钮 -->
        <a-button @click="showEmojiPicker" class="emoji-button">😀</a-button>
        <!-- <a-button @click="callPhone" class="emoji-button"><icon-phone /></a-button> -->
        <!-- 文件按钮 -->
        <a-button @click="openFilePicker" class="file-button">📎</a-button>
        <!-- 新增创建房间和加入房间按钮 -->
        <a-button @click="throwError" class="emoji-button">test</a-button>

        <a-button @click="createRoom" class="emoji-button">创建通话</a-button>
        <a-button @click="joinRoom" class="emoji-button">加入通话</a-button>
        <a-button @click="caoZuo" class="emoji-button">操作</a-button>
        <!-- 新增屏幕共享按钮 -->
        <a-button @click="startScreenSharing" class="emoji-button">屏幕共享</a-button>
        <!-- 新增进度条展示区域 -->
        <div v-if="isUploading" class="upload-progress">
          <div :style="{ width: `${uploadProgress}%`, background: 'blue' }" class="progress-bar"></div>
          <span>{{ uploadProgress }}%</span>
        </div>
        <!-- 新增上传结果提示区域 -->
        <div v-if="uploadResultMessage" class="upload-result">
          <span :class="uploadSuccess? 'success-message' : 'error-message'">{{ uploadResultMessage }}</span>
        </div>
      </div>
      <!-- 表情选择器 -->
      <div v-if="isEmojiPickerVisible" class="emoji-picker">
        <div v-for="emoji in emojis" :key="emoji" @click="selectEmoji(emoji)">
          <!-- 直接显示 Unicode 编码的 Emoji -->
          <span>{{ emoji }}</span>
        </div>
      </div>
     
      <!-- 文件选择器 -->
      <input type="file" ref="fileInput" @change="handleFileSelect" style="display: none" />
      <!-- 引入视频通话组件 -->
     <VideoCall
       :isVisible="isVideoCallVisible"
        :isCalling="isCalling"
      :currentUsername="currentUsername"
            :localStream="localStream"
        @answer="answerCall"
          @reject="rejectCall"
        @hangUp="hangUpCall"
        @update:isVisible="updateIsVideoCallVisible"
      />
    </div>
    
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import twemoji from 'twemoji';
import { uploadFile, downloadWithAxios } from '@/api/upload.ts';
import axios from 'axios';
import VideoCall from './component/VideoCall.vue';
import {createRoomApi} from '@/api/room.ts';
import {usePageStore} from '@/store/modules/page/index.ts';
// 新增监控DOM节点报错的逻辑
const observeDOMErrors = () => {
  const observer = new MutationObserver((mutationsList) => {
    for (const mutation of mutationsList) {
      if (mutation.type === 'childNodes') {
        // 处理节点变化，可根据具体需求添加错误处理逻辑
        console.log('DOM节点发生变化');
      }
    }
  });
  const targetNode = document.body;
  const config = { childList: true, subtree: true };
  observer.observe(targetNode, config);
  return () => {
    observer.disconnect();
  };
};
const messages = ref([
  { text: '欢迎来到对话页面！', isUser: false, username: '系统' },
]);
const inputMessage = ref('');
const currentUsername = ref('我');
const socket = ref(null);
const isEmojiPickerVisible = ref(false);
const emojis = ref(['😀', '😃', '😄', '🥳', '🤔']);
const fileInput = ref(null);
const isUploading = ref(false);
const uploadProgress = ref(0);
const uploadResultMessage = ref('');
const uploadSuccess = ref(false);


// 视频通话相关变量
const isVideoCallVisible = ref(false);
// Bug 修复：移除多余空格，使用 const 声明响应式变量
let isCalling = ref(false);
// 竖条选择菜单相关变量
const isSlashMenuVisible = ref(false);
const slashMenuOptions = ref([ { label: '无序列表', value: 'unorderedList' }, { label: '有序列表', value: 'orderedList' }, { label: '任务列表', value: 'taskList' }, { label: 'H，一级标题', value: 'heading1' }, { label: 'H2二级标题', value: 'heading2' }, { label: 'H三级标题', value: 'heading3' }, { label: '选项', value: 'option' }, { label: '正文', value: 'paragraph' }]);
// 处理输入事件
const handleInput = (event) => {
  if (event === '/') {
    isSlashMenuVisible.value = true;
  } else {
    isSlashMenuVisible.value = false;
  }
  // 处理列表样式
  if (inputMessage.value.startsWith('- ')) {
    // 处理无序列表
    inputMessage.value = `<ul><li>${inputMessage.value.slice(2)}</li></ul>`;
  } else if (/^\d+\. /.test(inputMessage.value)) {
    // 处理有序列表
    inputMessage.value = `<ol><li>${inputMessage.value.split('. ')[1]}</li></ol>`;
  }
};
// 选择选项
const selectOption = (option) => {
  inputMessage.value = option.label;
  isSlashMenuVisible.value = false;
};
const callStartTime = ref(null);
const callEndTime = ref(null);
const localStream = ref(null);
const peerConnection = ref(null);
const roomId = ref('');

const router = useRouter();
const route = useRoute();

setTimeout(() => {
  console.log(1);
  usePageStore.setLoading(true)
}, 5000);

// 初始化 WebSocket 连接
import { initWebSocket, handleQueryParams } from '@/utils/websocket.js';
onMounted(() => {
  initWebSocket(currentUsername, socket, messages, route, router);
  clickOutsideHandler = (event) => {
    if (isEmojiPickerVisible.value &&!event.target.closest('.emoji-picker') &&!event.target.closest('.emoji-button')) {
      isEmojiPickerVisible.value = false;
    }
  };
  document.addEventListener('click', clickOutsideHandler);
  // 调用监控函数
  observeDOMErrors();
});

// 发送消息的函数
const sendMessage = () => {
  if (inputMessage.value.trim()!== '') {
    console.log(
      '发送消息:', inputMessage.value
    );
    if (socket.value && socket.value.readyState === WebSocket.OPEN) {
      let uerInfo = localStorage.getItem('userInfo');
      let userInfo = JSON.parse(uerInfo);
      currentUsername.value = userInfo.username;
      const message = {
        message: inputMessage.value,
        isUser: true,
        username: userInfo.username,
        userid: userInfo.userid,
        userbid: userInfo.userbid
      };
      socket.value.send(JSON.stringify(message));
      inputMessage.value = '';
    }
  }
};

// 显示表情选择器
const showEmojiPicker = () => {
  isEmojiPickerVisible.value = true;
};

// 选择表情
const selectEmoji = (emoji) => {
  isEmojiPickerVisible.value = false;
  inputMessage.value += emoji;
};

// 打开文件选择器
const openFilePicker = () => {
  fileInput.value.click();
};

// 处理文件选择
const handleFileSelect = async (event) => {
  const file = event.target.files?.[0];
  if (file) {
    try {
      isUploading.value = true;
      uploadResultMessage.value = '';
      const result = await uploadFile(file, 'upload', (progress) => {
        uploadProgress.value = progress;
      });
      console.log('上传成功:', result);
      uploadSuccess.value = true;
      uploadResultMessage.value = '上传完成';
      // 上传成功后，通过 WebSocket 发送文件信息
      if (socket.value && socket.value.readyState === WebSocket.OPEN) {
        let uerInfo = localStorage.getItem('userInfo');
        let userInfo = JSON.parse(uerInfo);
        const fileMessage = {
          username: userInfo.username,
          file: {
            name: file.name,
            url: `/download/${result}` // 假设后端提供的下载接口
          }
        };
        socket.value.send(JSON.stringify(fileMessage));
      }
    } catch (error) {
      console.error('上传失败:', error);
      uploadSuccess.value = false;
      uploadResultMessage.value = '网络错误';
    } finally {
      isUploading.value = false;
      uploadProgress.value = 0;
    }
  }
};

// 使用 Twemoji 渲染包含 Emoji 的消息
const renderMessageWithEmoji = (text) => {
  if (typeof text === 'string') {
    return twemoji.parse(text);
  }
  return '';
};


// 点击文件名时触发的下载函数
const downloadFile = (message) => {
  const match = message.text.match(/<a href="\/download\/([^"]+)" download="([^"]+)"/);
  if (match && match.length === 3) {
    const fileUrl = `/download/${match[1]}`;
    const fileName = match[2];
    downloadWithAxios(fileUrl, fileName);
  }
};

let clickOutsideHandler;

onBeforeUnmount(() => {
  if (socket.value) {
    socket.value.close();
  }
  document.removeEventListener('click', clickOutsideHandler);
  if (localStream.value) {
    localStream.value.getTracks().forEach(track => track.stop());
  }
  if (peerConnection.value) {
    peerConnection.value.close();
  }
});

const callPhone = () => {
  isVideoCallVisible.value = true;
  isCalling = true;
  // 发送视频通话请求给对方
  if (socket.value && socket.value.readyState === WebSocket.OPEN) {
    let uerInfo = localStorage.getItem('userInfo');
    let userInfo = JSON.parse(uerInfo);
    const callRequest = {
      type: 'videoCallRequest',
      username: userInfo.username,
      roomId: roomId.value
    };
    socket.value.send(JSON.stringify(callRequest));
  }
};

const answerCall = async () => {
  try {
    localStream.value = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
    const localVideo = document.createElement('video');
    localVideo.srcObject = localStream.value;
    localVideo.autoplay = true;
    localVideo.muted = true;
    document.querySelector('.video-call-popup .video-display').appendChild(localVideo);
    callStartTime.value = new Date();
    // 发送接通视频通话的消息给对方
    if (socket.value && socket.value.readyState === WebSocket.OPEN) {
      let uerInfo = localStorage.getItem('userInfo');
      let userInfo = JSON.parse(uerInfo);
      const answerMessage = {
        type: 'answerCall',
        username: userInfo.username,
        roomId: roomId.value
      };
      socket.value.send(JSON.stringify(answerMessage));
    }
    console.log('视频通话已接通');
  } catch (error) {
    console.error('无法打开摄像头或麦克风，请检查设备权限。', error);
  }
};

const rejectCall = () => {
  isVideoCallVisible.value = false;
  isCalling = false;
  // 发送拒绝视频通话的消息给对方
  if (socket.value && socket.value.readyState === WebSocket.OPEN) {
    let uerInfo = localStorage.getItem('userInfo');
    let userInfo = JSON.parse(uerInfo);
    const rejectMessage = {
      type:'rejectCall',
      username: userInfo.username,
      roomId: roomId.value
    };
    socket.value.send(JSON.stringify(rejectMessage));
  }
  if (callStartTime.value) {
    callEndTime.value = new Date();
    const duration = (callEndTime.value - callStartTime.value) / 1000;
    const minutes = Math.floor(duration / 60);
    const seconds = Math.floor(duration % 60);
    messages.value.push({
      text: `${currentUsername.value} 和对方聊了 ${minutes} 分 ${seconds} 秒`,
      isUser: false,
      username: '系统'
    });
    callStartTime.value = null;
    callEndTime.value = null;
  }
  if (localStream.value) {
    localStream.value.getTracks().forEach(track => track.stop());
  }
  if (peerConnection.value) {
    peerConnection.value.close();
  }
  console.log('视频通话已拒绝');
};

const hangUpCall = () => {
  isVideoCallVisible.value = false;
  isCalling = false;
  callEndTime.value = new Date();
  const duration = (callEndTime.value - callStartTime.value) / 1000;
  const minutes = Math.floor(duration / 60);
  const seconds = Math.floor(duration % 60);
  messages.value.push({
    text: `${currentUsername.value} 和对方聊了 ${minutes} 分 ${seconds} 秒`,
    isUser: false,
    username: '系统'
  });
  callStartTime.value = null;
  callEndTime.value = null;
  if (localStream.value) {
    localStream.value.getTracks().forEach(track => track.stop());
  }
  if (peerConnection.value) {
    peerConnection.value.close();
  }
  // 发送挂断视频通话的消息给对方（如果需要）
  if (socket.value && socket.value.readyState === WebSocket.OPEN) {
    let uerInfo = localStorage.getItem('userInfo');
    let userInfo = JSON.parse(uerInfo);
    const hangUpMessage = {
      type: 'hangUpCall',
      username: userInfo.username,
      roomId: roomId.value
    };
    socket.value.send(JSON.stringify(hangUpMessage));
  }
  console.log('视频通话已挂断');
};

const updateIsVideoCallVisible = (newValue) => {
  isVideoCallVisible.value = newValue;
};
const throwError = () => {
  throw new Error('这是一个测试错误');
};
const createRoom = async () => {
  const roomNumber = ref(Math.floor(Math.random() * 1000000));
  let uerInfo = localStorage.getItem('userInfo');
  let userInfo = JSON.parse(uerInfo);
  const dataToSend = {
    ...userInfo,
    roomNumber: roomNumber.value
  };
  await createRoomApi(dataToSend).then((response) => {
    console.log(response);
    console.log('创建房间成功:', response);
    router.push({ name: 'room' ,params: { roomId: roomNumber.value }});
  }).catch((error) => {
    console.error('创建房间失败:', error);
  });
};
const joinRoom = async () => {
  const inputRoomId = prompt('请输入房间号：');
  router.push({ name: 'room' ,params: { roomId: inputRoomId }});
};
const caoZuo = async () => {
  router.push({ name: 'enter' });
};

// 后续可添加视频通话和屏幕共享的相关请求逻辑
const goToRoom = () => {
  router.push({ name: 'room' });
};

const startScreenSharing = async () => {
  try {
    const screenStream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: false });
    if (peerConnection.value) {
      const videoTracks = screenStream.getVideoTracks();
      if (videoTracks.length > 0) {
        const sender = peerConnection.value.getSenders().find(s => s.track && s.track.kind === 'video');
        if (sender) {
          sender.replaceTrack(videoTracks[0]);
        }
      }
    }
  } catch (error) {
    console.error('无法开始屏幕共享:', error);
  }
};

</script>



<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 80vh;
  background-color: #f8f9fa;
  padding: 20px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  position: relative;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  border: 1px solid #dee2e6;
  border-radius: 10px;
  padding: 15px;
  background-color: #fff;
  margin-bottom: 15px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.05);
}

.message {
  margin-bottom: 15px;
  display: block;
  clear: both; /* 清除浮动，避免布局混乱 */
}

.user-message,
.other-message {
  max-width: 60%;
  word-wrap: break-word;
  word-break: normal;
  padding: 10px 15px;
  border-radius: 10px;
  margin-bottom: 10px;
}

.user-message {
  display: flex;
  justify-content: flex-end;
  background-color: #d9edf7;
  border-radius: 10px 10px 0 10px;
  float: right; /* 让用户消息靠右浮动 */
}

.other-message {
  background-color: #e9ecef;
  border-radius: 10px 10px 10px 0;
  float: left; /* 让其他消息靠左浮动 */
}

.user-message a,
.other-message a,
.user-message code,
.other-message code {
  word-break: break-all;
}

.chat-input {
  display: flex;
  gap: 10px;
  align-items: center;
}

.input-box {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #ced4da;
  border-radius: 20px;
  font-size: 14px;
}

.send-button,
.emoji-button,
.file-button {
  padding: 10px 15px;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
}

.send-button {
  background-color: #007bff;
  color: #fff;
}

.emoji-button,
.file-button {
  background-color: #6c757d;
  color: #fff;
}

.emoji-picker {
  position: absolute;
  bottom: 60px;
  right: 20px;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 10px;
  padding: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.emoji {
  cursor: pointer;
  font-size: 20px;
  width: 30px;
  height: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
}

input[type="file"] {
  display: none;
}

.upload-progress {
  height: 20px;
  background-color: #f0f0f0;
  border-radius: 10px;
  overflow: hidden;
  margin-top: 10px;
}

.progress-bar {
  height: 100%;
  text-align: center;
  line-height: 20px;
  color: white;
}

.upload-result {
  margin-top: 10px;
}

.success-message {
  color: green;
}

.error-message {
  color: red;
}

.slash-menu {
  position: absolute;
  top: 80%;
  left: 20%;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 999; /* 添加z-index属性让菜单悬浮显示 */
  padding: 10px; /* 增加内边距，使列表更美观 */
  min-width: 150px; /* 设置最小宽度，避免菜单过窄 */
}
.slash-menu div {
  padding: 5px 10px; /* 增加选项的内边距，使选项更美观 */
  cursor: pointer; /* 鼠标悬停时显示手型 */
}
.slash-menu div:hover {
  background-color: #f0f0f0; /* 鼠标悬停时改变背景颜色 */
}
</style>